import React from 'react';
import menuRoute from 'routes/menuRoute'
import moment from 'moment'
import {deepFullCopy, messages} from 'share/common'
import { Form, Affix, Button, Row, Col, List, Tag, Dropdown, Menu, Icon, Spin, Divider } from 'antd'
import documentService from 'containers/setting/help-document-management/help-document.service'
import 'styles/setting/help-document-management/help-document-history.scss'
import { connect } from 'react-redux'

class HelpDocumentHistory extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      activeHistoryIndex: 0,
      chapterNames: [], //章节名称
      historyList: [],
      info: {},
      language: 'zh_cn',
      docTitle: '', //章节名称
      docContent: '', //章节内容
    }
  }

  componentDidMount() {
    this.getMenuList();
    this.getHistoryList()
  }

  //获取目录列表
  getMenuList = () => {
    documentService.getDocumentMenu().then(res => {
      this.getChapterNames(res.data)
    })
  };

  //获取章节路径
  getChapterNames = (items) => {
    let list = [];
    let chapterNames = [];
    let getMenuList = arr => {
      arr.map(item => {
        list.push(item);
        item.children && getMenuList(item.children)
      })
    };
    getMenuList(items);
    let getParentIDList = id => {
      if (id && id !== '0') { //非一级目录
        list.map(item => {
          if (item.id === id) {
            chapterNames.push(item.docTitle);
            getParentIDList(item.parentId)
          }
        })
      }
    };
    getParentIDList(this.props.params.id);
    chapterNames.reverse();
    this.setState({ chapterNames })
  };

  //获取历史信息列表
  getHistoryList = () => {
    let params = {
      id: this.props.params.id,
      language: 'zh_cn',
      page: 0,
      size: 12
    };
    this.setState({ loading: true });
    documentService.getHistoryList(params).then(res => {
      if (res.data && res.data.length) {
        this.getHistoryContent(res.data[0].id);
        this.setState({ historyList: res.data })
      } else {
        this.setState({ loading: false })
      }
    })
  };

  //获取历史信息详情
  getHistoryContent = (id) => {
    let params = {
      historyId: id,
      language: 'zh_cn'
    };
    this.setState({ loading: true });
    documentService.getHistoryContent(params).then(res => {
      this.setState({
        loading: false,
        info: res.data,
        docTitle: this.getDocTitleOrContent(res.data.i18n.docTitle, 'zh_cn'),
        docContent: this.getDocTitleOrContent(res.data.i18n.docContent, 'zh_cn'),
      })
    })
  };

  //获取文档标题或内容
  getDocTitleOrContent = (list, language) => {
    let value = '';
    list.map(item => {
      if (item.language === language)
        value = item.value
    });
    return value
  };

  //查看历史详情
  viewHistoryContent = (index) => {
    if (index !== this.state.activeHistoryIndex) {
      this.getHistoryContent(this.state.historyList[index].id);
      this.setState({ activeHistoryIndex: index })
    }
  };

  //修改语言
  handleLanguageChange = (key) => {
    this.setState({
      language: key,
      docTitle: this.getDocTitleOrContent(this.state.info.i18n.docTitle, key),
      docContent: this.getDocTitleOrContent(this.state.info.i18n.docContent, key),
    })
  };

  //编辑
  handleEdit = (e, historyID) => {
    e.stopPropagation();
    this.context.router.push(menuRoute.getPageUrlByKey('help-document-edit')
      .replace(':id', this.props.params.id)
      .replace(':historyID', historyID))
  };

  //返回
  goBack = () => {
    window.history.back(-1);
  };

  //渲染章节路径
  renderChapterRouter = () => {
    const chapterNames = deepFullCopy(this.state.chapterNames);
    let current = chapterNames.splice(chapterNames.length - 1, 1);
    return (
      <span>
        {chapterNames.join(' - ')}
        {chapterNames.length ? ' - ' : ''}
        <span>{current[0]}</span>
      </span>
    )
  };

  render() {
    const { loading, activeHistoryIndex, historyList, language, docTitle, docContent } = this.state;
    let lanObj = [
      {value: "zh_cn", label: messages('basic-11.key140')/*简体中文*/},
      {value: "zh_tw", label: messages('basic-11.key141')/*繁体中文*/},
      {value: "en", label: messages('basic-11.key142')/*英文*/},
      {value: "ja", label: messages('basic-11.key143')/*日语*/},
      {value: "it_IT", label: messages('basic-11.key144')/*意大利语*/},
    ];
    let languagesObj = {
      zh_cn: messages('basic-11.key140')/*简体中文*/,
      zh_tw: messages('basic-11.key141')/*繁体中文*/,
      en: messages('basic-11.key142')/*英文*/,
      ja: messages('basic-11.key143')/*日语*/,
      it_IT: messages('basic-11.key144')/*意大利语*/
    };
    const languageMenu = (
      <Menu onClick={e => this.handleLanguageChange(e.key)}>
        {
          lanObj.map(item => {return <Menu.Item key={item.value}>{item.label}</Menu.Item>})
        }
      </Menu>
    );
    return (
      <div className="help-document-history">
        <Spin spinning={loading}>
          <Row>
            <Col span={18} className="history-show-container">
              <div className="standard-divider-title title-path-area">
                {this.renderChapterRouter()}
              </div>
              {historyList.length ? (
                <div className="content-document">
                  <div className="document-header">
                    <span className="title">{docTitle || '-'}</span>
                    <Dropdown overlay={languageMenu}>
                      <a className="language">
                        {languagesObj[language]}<Icon type="down" />
                      </a>
                    </Dropdown>
                  </div>
                  <div className="document-content" dangerouslySetInnerHTML={{__html: docContent}} />
                </div>
              ) : (
                <div className="content-document no-history">
                  {!loading && messages('basic-11.key145')/*当前文档暂无发布历史*/}
                </div>
              )}
            </Col>
            <Col span={6} className="history-list-container">
              <List itemLayout="horizontal"
                    dataSource={historyList}
                    renderItem={(item, index) => (
                      <List.Item key={item.id}
                                 className={`${index === activeHistoryIndex ? 'active' : ''}`}
                                 onClick={() => this.viewHistoryContent(index)}>
                        <List.Item.Meta
                          title={(
                            <div>
                              {item.userName}&nbsp;&nbsp;
                              {moment(item.publishDate).format('YYYY-MM-DD HH:mm')}&nbsp;&nbsp;
                              {index === 0 ? <Tag color="blue">{messages('basic-11.key146')/*当前版本*/}</Tag> : ''}
                            </div>
                          )}
                          description={<a onClick={e => this.handleEdit(e, item.id)}>{messages('common.edit')/*编辑*/}</a>}
                        />
                      </List.Item>
                    )}
              />
            </Col>
          </Row>
        </Spin>
        <Affix className="bottom-bar" offsetBottom={0}>
          <Button onClick={this.goBack}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

HelpDocumentHistory.contextTypes = {
  router: React.PropTypes.object
};

HelpDocumentHistory.propTypes = {};

function mapStateToProps(state) {
  return {
  }
}

const WrappedHelpDocumentHistory = Form.create()(HelpDocumentHistory);
export default connect(mapStateToProps)(WrappedHelpDocumentHistory);
